<?php
/**
 * Created by PhpStorm.
 * User: Admin
 * Date: 2017/5/25
 * Time: 14:54
 */

namespace pc\controllers;

use common\controllers\ComController;
use yii;
use yii\helpers\Url;
use yii\gatewaywork\Gateway;
class ChatController extends ComController
{
    public $enableCsrfValidation = false;
    public function actionIndex()
    {
        $roomId = Yii::$app->request->get("room_id",0);
        if(empty($roomId) || !is_numeric($roomId) || $roomId < 0){
            echo "别乱搞啊";exit;
        }
        $this->assign("room_id",$roomId);
        $this->assign("bindUid",Url::toRoute('chat/bind'));
        $this->assign("sayUrl",Url::toRoute('chat/say'));
        return $this->display("index");
    }

    /**
     * 将websocket返回的client_id与当前的登录用户做绑定
     * @return string
     */
    public function actionBind(){
        $roomId = Yii::$app->request->post("room_id",0);
        $clientId = Yii::$app->request->post("client_id",0);
        $name = rand(pow(10,(6)), pow(10,7)-1);
        if(empty($roomId) || !is_numeric($roomId) || $roomId < 0 ||empty($clientId)){
            return json_encode(["flag"=>0,"msg"=>"faliure"]);
        }

        // 设置GatewayWorker服务的Register服务ip和端口，请根据实际情况改成实际值
        Gateway::$registerAddress = '127.0.0.1:1237';
        // 假设用户已经登录，用户uid和群组id在session中
        $uid      = session_id();
        Yii::$app->session->set("username",$name);
        Yii::$app->session->set("clientId",$clientId);
        // client_id与uid绑定
        Gateway::bindUid($clientId, $uid);
        //将当前用户进入房间的信息下发到同房间里的其他人
        Gateway::sendToGroup($roomId,json_encode(['type'=>'login','username'=>$name]));
        // 加入某个群组（可调用多次加入多个群组）
        Gateway::joinGroup($clientId, $roomId);
        return json_encode(["flag"=>1,"msg"=>"连接成功",'name'=>$name]);
    }
    public function actionSay(){
        Gateway::$registerAddress = '127.0.0.1:1237';
        $client_id = Yii::$app->session->get('clientId');//当前用户
        $room_id = Yii::$app->request->post("room_id",0);
        $chat = Yii::$app->request->post("chat","");
        $username = Yii::$app->session->get("username");
        $chat_time_last = Yii::$app->session->get($client_id."_chat_time_last");
        if(empty($chat_time_last)){
            $chat_time_last = 0;
            Yii::$app->session->set($client_id."_chat_time_last",time());
        }else{
            if($chat_time_last - time() == 120){
                Yii::$app->session->set($client_id."_chat_time_last",$chat_time_last + 120);
            }
        }
        $message_data['say_time'] = date("Y-m-d H:i:s",time());
        $message_data['username'] = $username;
        $message_data['type'] = "say";
        $message_data['chat'] = trim($chat);
        $message_data['chat_time'] =  $chat_time_last - time() >= 120 ?date("H:i:s",time()):0;
        $message_data['group'] = Gateway::getClientSessionsByGroup($room_id);
//        //自己发言，把信息先发送给自己，然后再发送给自己进的房间里的其他人
        $message_data['say_type'] = 1;
        Gateway::sendToClient($client_id,json_encode($message_data));
//        //将stype变成2 ，推送给其他人
        $message_data['say_type'] = 2;
        GateWay::sendToGroup($room_id,json_encode($message_data),[$client_id]);
        return json_encode(['flag'=>1]);
    }
}